package dp_package.all;

import java.util.HashMap;
import java.util.Map;

/**
 * todo
 *
 * @author luolidong
 * @version 1.0
 * @create 2021-08-05 15:15
 */
public class L377 {
    /*递归
    int count=0;
    public int combinationSum4(int[] nums, int target) {
        dfs(nums, target);
        return count;
    }
//    不需要index,因为每次从0开始
    public void dfs(int[] nums, int target){
        if(target<0) return;
        if(target==0){
            count++;
            return;
        }
        for (int i=0;i<nums.length;i++) {
            target -= nums[i];
            dfs(nums, target);
            target += nums[i];
        }
    }
     */
    //记忆法递归
    Map<Integer, Integer> map = new HashMap<>();

    public int combinationSum4(int[] nums, int target) {
        return dfs(nums, target);
    }

    private int dfs(int[] nums, int target) {
        if (target < 0) return 0;
        if (target == 0) return 1;

        if (map.get(target) != null) {
            return map.get(target);
        }
        int value = 0;
        for (int i = 0; i < nums.length; i++) {
            value += dfs(nums, target - nums[i]);
        }
        map.put(target, value);
        return value;
    }

    public static void main(String[] args) {
        L377 l377 = new L377();
        int i = l377.combinationSum4(new int[]{1, 2, 3}, 4);
        System.out.println(i);
    }
}
